/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/sort-comp */
/* eslint-disable import/no-extraneous-dependencies */
import { Button, Col, DatePicker, Form, Input, Row, Select, message, Popover } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import React, { PureComponent } from 'react';
import ExpressInfoModal from '@/components/ExpressInfoModal';
import PropTypes from 'prop-types';
import KbPreviewImage from '@/components/KbPreviewImage';
import { changePostName } from '@/utils/changePostCompanyName';
import { getLStorage } from '@/utils/utils';
import Tables from '../Tables';

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;

// 快递品牌显示的选项，数组有多少成员，显示多少品牌。
const brands = ['all', 'sto', 'zt', 'yt', 'yd', 'jt', 'ems'];
@connect(({ allocation, setting, user }, { type }) => ({
  user_info: user.currentUser.user_info,
  allocation,
  brandType: allocation[`${type}Brand`],
  branchInfo: allocation[`${type}BranchInfo`],
  brandCode: allocation[`${type}BrandCode`],
  ...setting,
}))
@Form.create()
export default class ScanRecord extends PureComponent {
  state = {
    defaultBrand: 'all',
  };

  constructor(props) {
    super(props);
    const { type } = props;
    this.columns = [
      {
        title: '快递品牌',
        dataIndex: 'brand',
        key: 'brand',
        align: 'center',
        width: 100,
      },
      {
        title: '网点编号',
        dataIndex: 'branch_no',
        key: 'branch_no',
        align: 'center',
        width: 100,
      },
      {
        title: '运单号',
        dataIndex: 'waybill_no',
        key: 'waybill_no',
        align: 'center',
        width: 200,
        render: (text, record) => (
          <Row type="flex" justify="center" align="middle" gutter={[20, 0]}>
            <Col>
              <a onClick={this.showExpressModal.bind(this, record)}>{text}</a>
            </Col>
            {record.sign_pic &&
              type !== 'sign' && (
                <Col>
                  <KbPreviewImage src={record.sign_pic} />
                </Col>
              )}
          </Row>
        ),
      },
      {
        title: '扫描员',
        align: 'center',
        width: 200,
        render: record => <div>{`${record.cm_name} ${record.cm_phone}`}</div>,
      },
      {
        title: '是否推送',
        dataIndex: 'send_status',
        key: 'send_status',
        align: 'center',
        width: 100,
      },
      {
        title: '失败原因',
        dataIndex: 'fail_desc',
        key: 'fail_desc',
        align: 'center',
        width: 100,
        render: (text, record) => {
          const { send_status, fail_desc } = record;
          const content = (
            <div>
              <p>{fail_desc}</p>
            </div>
          );
          return (
            <div>
              {send_status == '已推送' ? (
                ''
              ) : (
                <Popover autoAdjustOverflow={false} content={content} title="失败原因">
                  <Button type="link">详情</Button>
                </Popover>
              )}
            </div>
          );
        },
      },
      {
        title: '扫描时间',
        dataIndex: 'scan_time',
        key: 'scan_time',
        align: 'center',
        width: 200,
      },
      {
        title: '入库时间',
        dataIndex: 'create_time',
        key: 'create_time',
        align: 'center',
        width: 200,
      },
      {
        title: '推送时间',
        dataIndex: 'update_time',
        key: 'update_time',
        align: 'center',
        width: 200,
      },
    ];

    if (type === 'delivery') {
      this.columns.splice(
        4,
        0,
        {
          title: '派件员',
          align: 'center',
          width: 200,
          render: record => (
            <div>
              <span>{record.operator_name || ''}</span> <span>{record.courier_phone || ''}</span>
            </div>
          ),
        },
        {
          title: '三段码',
          align: 'center',
          width: 100,
          render: record => record['3rd_code'] || '',
        },
      );
    }
    if (type === 'sign') {
      this.columns.splice(
        4,
        0,
        {
          title: '签收人',
          dataIndex: 'sign_type',
          key: 'sign_type',
          align: 'center',
          width: 100,
        },
        {
          title: '签收图片',
          dataIndex: 'sign_pic',
          key: 'sign_pic',
          align: 'center',
          width: 100,
          render: sign_pic => (sign_pic ? <KbPreviewImage src={sign_pic} /> : null),
        },
      );
    }
    if (type === 'send') {
      this.columns.splice(4, 0, {
        title: '下一站',
        align: 'center',
        width: 100,
        render: record => (
          <div>
            <span>{record.next_station_name || ''}</span> <span>{record.next_station || ''}</span>
          </div>
        ),
      });
    }
    if (type === 'error') {
      this.columns.splice(
        4,
        0,
        {
          title: '问题件大类',
          align: 'center',
          dataIndex: 'bad_waybill_type',
          key: 'bad_waybill_type',
          width: 150,
        },
        {
          title: '问题件小类',
          align: 'center',
          dataIndex: 'bad_waybill_desc',
          key: 'bad_waybill_desc',
          width: 150,
        },
        {
          title: '问题件描述',
          align: 'center',
          dataIndex: 'bad_waybill_describe',
          key: 'bad_waybill_describe',
          width: 150,
        },
      );
    }
  }

  componentDidMount() {
    const { brand } = this.props;
    this.setState({
      defaultBrand: brand || 'all',
    });
  }

  handleBrandChange = value => {
    const { dispatch, type } = this.props;
    dispatch({
      type: 'allocation/save',
      payload: {
        [`${type}Brand`]: value,
        [`${type}BrandCode`]: 'all',
      },
    });
  };

  onBranchChange = value => {
    const { dispatch, type } = this.props;
    dispatch({
      type: 'allocation/save',
      payload: {
        [`${type}BrandCode`]: value,
      },
    });
  };

  // 展示物流
  showExpressModal = record => {
    const { allocation } = this.props;
    const { addressId, isZyAccount } = allocation;
    let branch_id;
    if (isZyAccount) {
      branch_id = [...addressId].pop();
    }
    const { id, waybill_no, brand, brand_name, create_time, cm_phone } = record;
    const expressInfo = {
      id,
      waybill_no,
      brand_name: brand,
      brand: brand_name,
      create_time,
      cm_phone,
      branch_id,
    };

    this.setState({
      expressInfo,
    });
  };

  changeFormType(reset = false, isExport) {
    /**
     * 拿到输入框内容，并处理相应格式
     * 时间格式处理成字符串,并且比对开始和结束时间
     * 判断是否有网点
     * 判断输入的是手机号还是姓名
     * 处理单号数据，转换成字符串，以逗号分开。
     */
    const { allocation, type, form, dispatch } = this.props;
    const { getFieldsValue, resetFields, setFieldsValue } = form;
    const { defaultBrand } = this.state;
    const { addressId = [], isZyAccount } = allocation;
    const brand = allocation[`${type}Brand`] || defaultBrand;
    const branchInfo = allocation[`${type}BranchInfo`] || {};
    const brandCode = allocation[`${type}BrandCode`] || 'all';
    // 重置查询条件
    if (reset) {
      resetFields();
      setFieldsValue({
        courier: '',
        waybill_no: '',
        send_status: '3',
        start_scan_time: null,
        end_scan_time: null,
        brand: 'all',
        cm_id: 'all',
        dispatch_phone: '',
      });
    }
    // 防止获取上一次的表单值
    const formValues = getFieldsValue();
    const data = { ...formValues };
    if (isZyAccount) {
      data.branch_id = [...addressId].pop();
    }
    const { end_scan_time, start_scan_time, waybill_no, courier } = data;

    // 开始和结束时间有就变格式，没有就给默认
    if (start_scan_time) {
      data.start_scan_time = moment(start_scan_time).format('YYYY-MM-DD HH:mm:ss');
    } else {
      data.start_scan_time = `${moment().format('YYYY-MM-DD')} 00:00:00`;
    }
    if (end_scan_time) {
      data.end_scan_time = moment(end_scan_time).format('YYYY-MM-DD HH:mm:ss');
    } else {
      data.end_scan_time = `${moment().format('YYYY-MM-DD')} 23:59:59`;
    }

    const inMonth = moment(data.end_scan_time).month() == moment(data.start_scan_time).month();

    if (new Date(data.end_scan_time).getTime() < new Date(data.start_scan_time).getTime()) {
      message.warning('扫描结束时间不可早于开始时间');
      return false;
    }

    if (!inMonth) {
      message.warn('不支持跨月查询，请重新选择查询区间');
      return false;
    }

    if (!reset && isExport != 'export' && brand == 'all') {
      message.warn('请选择需要查询的品牌');
      return false;
    }

    if (courier) {
      // /^[0-9]{11}$/
      if (new RegExp('^[0-9]+$').test(courier)) {
        if (new RegExp('^1[3-9][0-9][0-9]{8}$').test(courier)) {
          data.cm_phone = courier;
        } else {
          message.warning('手机号码格式有误');
          return false;
        }
      } else {
        data.cm_name = courier;
      }
    }
    if (waybill_no) {
      data.waybill_no = waybill_no.replace(/[\n,]/g, ',');
      const waybill_no_length = data.waybill_no.split(',').filter(i => i).length;
      if (waybill_no_length > 10) {
        message.error('最大支持10个单号的批量查询，已超过无法查询');
        return null;
      }
    }

    // 设置网点编号
    data.brand = brand;
    if (branchInfo[brand]) {
      if (brandCode == 'all') {
        data.branch_code = brandCode;
      } else {
        // eslint-disable-next-line prefer-destructuring
        data.branch_code = brandCode.split('-')[0];
      }
    } else if (brand != 'all') {
      message.warning('没有网点信息');
      return false;
    }

    // 重置查询条件
    if (reset) {
      data.brand = 'all';
      data.branch_code = 'all';
      dispatch({
        type: 'allocation/save',
        payload: {
          [`${type}Brand`]: 'all',
          [`${type}BrandCode`]: 'all',
          [`${type}ScanTableData`]: {
            list: [],
            total: 0,
            page: {},
          },
        },
      });
      return null;
    }

    return data;
  }

  exportExcel() {
    const { type, options, user_info, dispatch } = this.props;
    const data = this.changeFormType(false, 'export');
    const { phone, gp_area_ids = [], area_ids } = user_info || {};
    if (options.key == 'yz') {
      const isCompany = area_ids == '*';
      const cacheAreaId = getLStorage(`KB_GP_AREA_${phone}`);
      const reqAreaId = gp_area_ids.includes(cacheAreaId)
        ? cacheAreaId
        : isCompany
          ? '0'
          : gp_area_ids[0];
      data.area_id = reqAreaId;
    }
    // 可以直接导出，不用查询
    data.n_export = 'csv';
    type == 'delivery' && (data.waybill_type = '2');
    type == 'arrive' && (data.waybill_type = '5');
    type == 'sign' && (data.waybill_type = '3');
    type == 'send' && (data.waybill_type = '6');
    type == 'error' && (data.waybill_type = '4');

    dispatch({
      type: 'allocation/getScanSearch',
      payload: data,
    });
  }

  render() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 },
      },
    };
    const { defaultBrand, expressInfo } = this.state;
    const {
      search,
      dataSource,
      pagination,
      paginationChange,
      loading,
      queryData = {},
      brandType = defaultBrand,
      branchInfo = {},
      brandCode = 'all',
      form: { getFieldDecorator },
      type,
      user_info: { realAccount },
    } = this.props;
    const fakeAccount = realAccount == 2;
    let changeBranchInfo = null;
    const {
      start_scan_time,
      end_scan_time,
      courier,
      send_status,
      waybill_no,
      dispatch_phone,
    } = queryData; // 快递员看板透传查询的数据，从路由带入

    if (branchInfo[brandType]) {
      changeBranchInfo = [...branchInfo[brandType]];
    }

    const selectBrands = !fakeAccount ? brands : brands.filter(v => !['yd', 'yt'].includes(v));

    return (
      <Form>
        <Row>
          <Col span={16}>
            <Col span={12}>
              <FormItem {...formItemLayout} label="入库开始时间：">
                {getFieldDecorator('start_scan_time', {
                  initialValue: start_scan_time ? moment(start_scan_time) : null,
                })(
                  <DatePicker
                    style={{ width: '100%' }}
                    showTime
                    placeholder={`${moment().format('YYYY-MM-DD')} 00:00:00`}
                  />,
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="快递品牌：">
                {getFieldDecorator('brand', {
                  initialValue: brandType,
                })(
                  <Select onChange={this.handleBrandChange}>
                    {selectBrands.map(item => (
                      <Option key={item}>{changePostName(item, 'brand')}</Option>
                    ))}
                  </Select>,
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="是否推送：">
                {getFieldDecorator('send_status', {
                  initialValue: send_status || '3',
                })(
                  <Select
                    showSearch
                    optionFilterProp="children"
                    filterOption={(input, option) =>
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    <Option value="3">全部</Option>
                    <Option value="1">已推送</Option>
                    <Option value="2">未推送</Option>
                  </Select>,
                )}
              </FormItem>
              {type === 'delivery' ? (
                <FormItem {...formItemLayout} label="派件员：">
                  {getFieldDecorator('dispatch_phone', {
                    initialValue: dispatch_phone,
                  })(<Input allowClear maxLength={11} placeholder="请输入派件员手机号或姓名" />)}
                </FormItem>
              ) : null}
            </Col>
            <Col span={12}>
              <FormItem {...formItemLayout} label="入库结束时间：">
                {getFieldDecorator('end_scan_time', {
                  initialValue: end_scan_time ? moment(`${end_scan_time} 23:59:59`) : null,
                })(
                  <DatePicker
                    style={{ width: '100%' }}
                    showTime
                    placeholder={`${moment().format('YYYY-MM-DD')} 23:59:59`}
                  />,
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="网点编号：">
                <Select
                  value={
                    changeBranchInfo && changeBranchInfo.length != 0
                      ? changePostName(brandCode)
                      : '暂无数据'
                  }
                  onChange={this.onBranchChange}
                >
                  {changeBranchInfo && changeBranchInfo.length != 0 ? (
                    changeBranchInfo.map(item => <Option key={item}>{changePostName(item)}</Option>)
                  ) : (
                    <Option key="none">暂无数据</Option>
                  )}
                </Select>
              </FormItem>
              <FormItem {...formItemLayout} label="扫描员：">
                {getFieldDecorator('courier', {
                  initialValue: courier || '',
                })(<Input maxLength={11} placeholder="请输入扫描员手机号或姓名" />)}
              </FormItem>
            </Col>
          </Col>
          <Col span={8}>
            <Row>
              <Col span={7}>
                <div className="orderNumber">运单编号：</div>
              </Col>
              <Col span={16}>
                {getFieldDecorator('waybill_no', {
                  initialValue: waybill_no,
                })(
                  <TextArea
                    style={{ height: '120px', resize: 'none' }}
                    placeholder="请输入运单编号，多个运单编号按回车"
                  />,
                )}
              </Col>
            </Row>
            <Row className="button">
              <Col offset={7}>
                <Button
                  style={{ marginRight: 10 }}
                  type="primary"
                  icon="search"
                  onClick={() => search(this.changeFormType())}
                >
                  查询
                </Button>
                {!fakeAccount && (
                  <Button
                    style={{ marginRight: 10 }}
                    type="primary"
                    icon="download"
                    onClick={() => {
                      this.exportExcel();
                    }}
                  >
                    导出
                  </Button>
                )}
                <Button
                  type="primary"
                  icon="undo"
                  onClick={() => search(this.changeFormType(true))}
                >
                  重置
                </Button>
              </Col>
            </Row>
          </Col>
        </Row>
        <Row>
          <Tables
            scroll={{ x: 1200 }}
            className="table"
            dataSource={dataSource}
            columns={this.columns}
            bordered={false}
            pagination={pagination}
            paginationChange={e => {
              paginationChange(e);
            }}
            loading={loading}
            style={{ marginTop: '10px' }}
          />
        </Row>
        <ExpressInfoModal
          cleanData={() => {
            this.setState({
              expressInfo: null,
            });
          }}
          data={expressInfo}
          type="scanRecord"
        />
      </Form>
    );
  }
}

ScanRecord.propTypes = {
  type: PropTypes.oneOf(['delivery', 'arrive', 'send', 'sign', 'error']).isRequired,
};
